package com.gable.exhibition.service.impl;

import com.gable.exhibition.dao.HospitalDao;
import com.gable.exhibition.dao.SequenceDao;
import com.gable.exhibition.model.Hospital;
import com.gable.exhibition.service.SequenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

/**
 * Created by Lesson on 2018/2/26.
 */
@Service("sequenceService")
public class SequenceServiceImpl implements SequenceService {

    @Autowired
    SequenceDao sequenceDao;
    @Autowired
    HospitalDao hospitalDao;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public synchronized Long querySequence() {
        long num = sequenceDao.querySequence();
        long num1 = num+1;
        sequenceDao.updateSequenceNum(num1);
        return num;
    }

    @Override
    public  String getQrcode(Long hospitalId) {
        StringBuffer sb = new StringBuffer();
        sb.append("");
        try {
            Hospital hospital = hospitalDao.selectByPrimaryKey(hospitalId);
            String hospitalCode = hospital.getHospitalCode() == null ? "00000000" : hospital.getHospitalCode();
            sb.append(hospitalCode);
            Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            sb.append(year - 2000);
            int month = c.get(Calendar.MONTH) + 1;
            if (month < 10) {
                sb.append("0");
            }
            sb.append(month);
            int day = c.get(Calendar.DAY_OF_MONTH);
            if(day<10){
                sb.append("0");
            }
            sb.append(day);
            Long sequence = querySequence();
            sb.append(sequence);
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
}
